# ----------------------------------------------------------------------------
#       Copyright (C) 2013-2014 Huynh Vi Lam  <domovilam@gmail.com>
#
#       This file is part of pimucha.
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#	
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------

import logging

logger = logging.getLogger()


def chkcmdname(param,sdaemons):
    """
    param = [cmd,namedev]
    namedev = identify daemon
    namedev = name + ':' + idctrl
    """
    if isinstance(param,list):
        p = param
    else:
        p = param.split()
    if len(p) == 1:
        return None
    cmd = p[0]
    namedev = p[1]
    if namedev in sdaemons:
        dev = sdaemons[namedev]
        if cmd not in dev.servercmds:
            print ('Command %s unknown for %s' % (cmd,repr(dev)))
            return None
        else:
            return dev.servercmds[cmd],namedev,dev
    else:
        print ('Daemon %s not yet setup' % namedev)
        return None


def chkparsdaemon(param,sdaemons):
    if param in sdaemons:
        dev = sdaemons[param]
    else:
        logger.error('Controller Daemon not yet setup %s',param)
        return None
    p = param.split(':')
    name = p[0]
    ctrl = p[1]
    return dev,name,ctrl


def chksetup(param,sdaemons):
    """
    param = [name,idctrl-rxtx, port]
    name  = first position
    idctrl-rxtx = second position
          idcontroller '-' rxtx (case of net controller)
          rxtx in ['RX','TX']
    if 'SCTRL': port = needed for serial
                       needed for USB if many controllers of same type
    if 'NCTRL' or 'SRV': port = host:port
    """
    if isinstance(param,list):
        p = param
    else:
        p = param.split()
    if len(p) < 2: return None
    name = p[0]
    if '-' in p[1]:
        idctrl,rxtx = p[1].split('-')
        if rxtx not in ['RX','TX']: return None
    else:
        idctrl = p[1]
        rxtx = None
    if idctrl[0] == 'N' and rxtx is None: rxtx = 'RX'
    if len(p) == 2:
        port = 'Defaults'
    else:
        port = p[2]
    #Check if already setup
    namedev = name + ':' + idctrl
    if namedev in sdaemons:
        dev = sdaemons[namedev]
        if dev.setup:
             print ('%s already setup' % namedev)
             return None
        else:		# dev disconnected
             del sdaemons[namedev]
    return name, idctrl, port, rxtx
